<?php
namespace Controllers;

use Models\Book;

class BookController extends BaseController {

    /**
     * 显示图书列表
     */
    public function lists() {

        $bookModel = new Book();
        $result = $bookModel->getAllBooks();
        return $this->render('book/lists', ['items' => $result]);
    }

    /**
     * 添加图书
     */
    public function add() {
        if ($_POST) {
            $title = isset($_POST['title']) ? $_POST['title'] : '';
            if (empty($title)) return $this->error('请填写图书名称');
            $isbn = isset($_POST['isbn']) ? $_POST['isbn'] : '';
            if (empty($isbn)) return $this->error('请填写ISBN');
            $publish = isset($_POST['publish']) ? $_POST['publish'] : '';
            if (empty($publish)) return $this->error('请填写出版社');

            $bookModel = new Book();

            $result = $bookModel->addBook($title, $isbn, $publish);

            if ($result) {
                return $this->success('添加成功', '/index.php?c=book&a=lists');
            } else {
                return $this->error('添加失败');
            }
        } else {
            return $this->render('book/add');
        }

    }

    /**
     * 删除图书
     */
    public function delete() {
        $book_id = $_GET['book_id'];

        $bookModel = new Book();
        if ($bookModel->deleteBook($book_id)) {
            return $this->success('删除成功', '/index.php?c=book&a=lists');
        } else{
            return $this->error('删除失败');
        }
    }

    /**
     * 修改图书
     */
    public function edit() {
        if ($_POST) {
            $title = isset($_POST['title']) ? $_POST['title'] : '';
            if (empty($title)) return $this->error('请填写图书名称');
            $isbn = isset($_POST['isbn']) ? $_POST['isbn'] : '';
            if (empty($isbn)) return $this->error('请填写ISBN');
            $publish = isset($_POST['publish']) ? $_POST['publish'] : '';
            if (empty($publish)) return $this->error('请填写出版社');
            $stock = isset($_POST['stock']) ? $_POST['stock'] : 0;
            if ($stock < 0) return $this->error('库存不能小于0');

            $bookModel = new Book();
            if ($bookModel->updateBook($title, $isbn, $publish, $stock, $_POST['id']) !== false) {
                return $this->success('修改成功', '/index.php?c=book&a=lists');
            } else {
                return $this->error('修改失败');
            }

        } else {
            $book_id = $_GET['book_id'];

            $bookModel = new Book();
            $book = $bookModel->getBookById($book_id);
            return $this->render('book/edit', ['book' => $book]);
        }
    }

}